<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-button size="small" type="primary" class="filter-item" style="font-weight: bold;">礼物卡总数:{{ total }}</el-button>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item :label='$t("礼物卡编号")'>
          <el-input v-model="formInline.cardNo" :placeholder='$t("请输入礼物卡编号")' clearable></el-input>
        </el-form-item>
        <el-form-item :label='$t("礼物卡名称")'>
          <el-input v-model="formInline.name" :placeholder='$t("请输入礼物卡名称")' clearable></el-input>
        </el-form-item>
        <el-form-item :label="$t('时间')">
          <el-date-picker
            v-model="formInline.dateRange"
            type="datetimerange"
            start-placeholder="请选择开始时间"
            end-placeholder="请选择结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
            :picker-options="datePickerShortcuts"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('添加人')">
          <el-select v-model="formInline.userId" filterable clearable>
            <el-option v-for="item in userOptions" :key="item.id" :label="item.username" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label='$t("礼物卡分类")'>
          <el-select
            v-model="formInline.classificationId"
            clearable
            class="filter-item"
            :placeholder="$t('请选择礼物卡分类')"
          >
            <el-option
              v-for="item in cardList"
              :key="item.id"
              :value="item.id"
              :label="item.classificationName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label='$t("状态")'>
          <el-select v-model="formInline.status" :placeholder='$t("状态")' clearable>
            <el-option :label='$t("新增")' value="0"></el-option>
            <el-option :label='$t("已上架")' value="1"></el-option>
            <el-option :label='$t("已下架")' value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleFilter"
                     v-permission="['GET /admin/p/card_entity_index']">{{ $t('Search') }}
          </el-button>
          <el-button type="success" plain1 v-permission="['GET /admin/p/card_entity_add']" icon="el-icon-circle-plus"
                     @click="handleCreate">{{ $t('Add') }}
          </el-button>
          <el-button
            type="warning"
            icon="el-icon-folder-add"
            v-permission="[
              'GET /admin/p/activity_giftcardClassification_index',
            ]"
            @click="handlegiftClassification"
          >{{ $t("卡号分类") }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" stripe fit
              highlight-current-row>
      <el-table-column align="center" type="index" :label='$t("序号")'  :index="(index) => (formInline.page - 1) * formInline.limit + index + 1" width="50"></el-table-column>
      <el-table-column align="center" :label='$t("编码")' prop="cardNo"/>
      <el-table-column
        align="center"
        :label="$t('礼物卡分类')"
        prop="classificationName"
      />
      <el-table-column align="center" :label='$t("礼物卡名称")' prop="name"/>

      <el-table-column align="center" :label='$t("礼物卡图片")' prop="picUrl">
        <template slot-scope="scope">
          <el-image preview-src-list style="border-radius:7%;width:80px" :src="scope.row.picUrl" width="20" lazy>
            <div slot="error" class="image-slot">
              <i style="font-size: 30px" class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column align="center" :label='$t("数量")' prop="numbers">
        <template slot-scope="scope">
          <el-tag>
            {{ filterRanges(scope.row.numbers) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" :label='$t("礼物卡描述")' prop="desc"/> -->
      <el-table-column align="center" :label='$t("添加时间")' prop="addTime">
        <template slot-scope="scope">
          {{ formatDateToYYYYMMDD(scope.row.addTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label='$t("添加人")' prop="addUserName"/>
      <el-table-column align="center" :label='$t("状态")' prop="type">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0"><i class="el-icon-minus"></i>{{ $t('新增') }}</el-tag>
          <el-tag v-else-if="scope.row.status==1" type="success"><i class="el-icon-upload2"></i>{{ $t('已上架') }}
          </el-tag>
          <el-tag v-else-if="scope.row.status==2" type="info"><i class="el-icon-download"></i>{{ $t('已下架') }}
          </el-tag>
          <!--          <span>{{$t(scope.row.status==0?'新增':scope.row.status==1?"已上架":scope.row.status==2?'已下架':scope.row.status)}}</span>-->
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Operate')" width="300" class-name="small-padding fixed-width">
        <template slot="header" slot-scope="{row}">
          {{ $t('Operate') }}
          <i class="el-icon-s-tools" style="color: #d35e32"></i>
        </template>
        <template slot-scope="scope">
          <el-link style="margin-left: 5px" type="primary" icon="el-icon-view" v-if="scope.row.status==1" size="mini"
                   @click="handleDetail(scope.row)" v-permission="['GET /admin/p/card_entity_detail']">{{ $t("查看") }}
          </el-link>
          <el-link style="margin-left: 5px" type="primary" icon="el-icon-edit" v-if="scope.row.status!=1" size="mini"
                   @click="handleDetail(scope.row)" v-permission="['GET /admin/p/card_entity_edit']">{{ $t("编辑") }}
          </el-link>
          <el-link style="margin-left: 5px" type="warning" icon="el-icon-data-line" align="center"
                   v-if="scope.row.status!=0" size="mini" @click="handleEdit(scope.row)"
                   v-permission="['GET /admin/p/card_entity_statistic']">{{ $t("卡号统计") }}
          </el-link>
          <el-link style="margin-left: 5px" type="danger" icon="el-icon-delete" v-if="scope.row.status!=1" size="mini"
                   @click="handleDelete(scope.row)" v-permission="['GET /admin/p/card_entity_delete']">
            {{ $t('Delete') }}
          </el-link>
          <el-link style="margin-left: 5px" type="success" icon="el-icon-position" size="mini"
                   @click="handstatus(scope.row)" v-permission="['GET /admin/p/card_entity_status']">
            {{ scope.row.status == 0 ? $t('上架') : scope.row.status == 1 ? $t("下架") : scope.row.status == 2 ? $t('上架') : scope.row.status }}
          </el-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="formInline.page" :limit.sync="formInline.limit"
                @pagination="getList"/>

    <el-tooltip placement="top" :content="$t('Back_to_top')">
      <back-to-top :visibility-height="100"/>
    </el-tooltip>
  </div>
</template>
<script>
import ElSelectDropdown from 'element-ui/packages/select/src/select-dropdown'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import {listGiftCard, deleteGiftCard, updateStatus} from "@/api/gift";
import {datePickerShortcuts, formatDateToYYYYMMDD} from "../../utils/date";
import {cardClassificationList} from "@/api/cardClassification";
import {userOption} from "../../api/user";
export default {
  name: "giftcard",
  components: {ElSelectDropdown, BackToTop, Pagination},
  data() {
    return {
      datePickerShortcuts,
      //卡类型
      cardList: [],
      formInline: {
        dateRange:[],
        userId:undefined,
        cardNo: '',
        name: '',
        type: 2,
        status: '',
        page: 1,
        limit: 10,
      },
      list: [],
      total: 0,
      listLoading: false,
      userOptions: [],
    }
  },
  created() {
    this.getList()
    this.getCardClassification();
    this.getUser();
  },
  methods: {
    formatDateToYYYYMMDD,
    getUser() {
      userOption({ keyword: undefined })
        .then(response => {
          this.userOptions = response.data.data
        })
        .catch(() => {
          this.userOptions = []
        })
    },
    //获取卡类型列表
    getCardClassification() {
      var formInline = {
        classificationName: undefined,
        classificationStatus: undefined,
        page: 1,
        limit: 1000,
        sort: "add_time",
        order: "desc",
      };
      cardClassificationList(formInline)
        .then((response) => {
          this.cardList = response.data.data.list;
        })
        .catch(() => {
          this.cardList = [];
        });
    },
    getList() {
      this.listLoading = true
      listGiftCard(this.formInline).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    filterRanges(numbers) {
      if (numbers == 0) {
        return this.$t('无限量')
      } else {
        return '' + numbers
      }
    },
    handleDelete(row) {
      this.$confirm(this.$t('Confirm_Delete?'), this.$t('Hint'), {
        confirmButtonText: this.$t('Confirm'),
        cancelButtonText: this.$t('Cancel'),
        type: 'warning'
      }).then(() => {
        this.doDelete(row)
      });
    },
    doDelete(row) {
      deleteGiftCard(row.id).then(response => {
        this.$notify.success({
          title: this.$t('Success!'),
          message: this.$t('Deleted')
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }).catch(response => {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t(response.data.errmsg)
        })
      })
    },
    handleFilter() {
      this.getList()
    },
    handleCreate() {//新增
      this.$router.push({path: '/promotion/giftcard/create', query: {type: 2}})
    },
    handleEdit(row) {//卡号统计
      this.$router.push({path: '/promotion/cardStatistics/cardStatisticsdetail', query: {id: row.id, status: 0}})
    },
    handleDetail(row) {//跳转详情
      this.$router.push({
        path: '/promotion/giftcard/edit',
        query: {id: row.id, type: 2, showType: row.status == 1 ? 2 : 1}
      })
    },
    handlegiftClassification() {
      //礼物卡分类
      this.$router.push({path: "/promotion/giftcardClassification"});
    },
    handstatus(row) {
      this.open(row)
    },
    open(row) {
      var mag = row.status == 0 ? '上架' : row.status == 1 ? "下架" : row.status == 2 ? '上架' : row.status
      this.$confirm(this.$t('确定') + mag + this.$t('吗?, 是否继续?'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        updateStatus(row.id).then(res => {
          this.$message({
            type: 'success',
            message: mag + this.$t('成功!')
          });
          this.getList()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('取消成功')
        });
      });
    },

  }
}
</script>

<style scoped>

.daytime {
  color: #606266;
  font-size: 14px;
  font-weight: 700;
}
</style>
